﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace GPMS.Web.Controllers
{
    using GPMS.BLL;
    using GPMS.Model;
    using Webdiyer.WebControls.Mvc;
    using System.Web.Security;
    public class FileController : BaseController
    {

        public ActionResult Upload()
        {
            return View();
        }

        [HttpPost]
        public void Upload(HttpPostedFileBase FileData, string folder, string name)
        {
            try
            {
                Guid userid = Guid.Parse(FormsAuthentication.Decrypt(Request["token"]).UserData);
                GPMS.Model.File file = new Model.File()
                {
                    FileID = Guid.NewGuid(),
                    FileType = FileType.Normal.ToString(),
                    MimeType = FileData.ContentType,
                    Size = FileData.ContentLength,
                    Name = Path.GetFileName(FileData.FileName),
                    UserInfoUserID = userid
                };
                FileHelper.Add(file, gpmsDb);
                DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/upload"));
                if (!dir.Exists)
                {
                    dir.Create();
                }
                FileData.SaveAs(Path.Combine(Server.MapPath("~/upload"), file.FileID.ToString()));

                Response.Write("成功上传：" + file.Name);
            }
            catch (Exception ex)
            {
                Response.Write("上传失败！" + ex.Message);
            }
            
        }

        [HttpPost]
        public void UploadIcon(HttpPostedFileBase FileData, string folder, string name)
        {
            try
            {
                Guid userid = Guid.Parse(FormsAuthentication.Decrypt(Request["token"]).UserData);
                GPMS.Model.File file = new Model.File()
                {
                    FileID = Guid.NewGuid(),
                    FileType = FileType.Icon.ToString(),
                    MimeType = FileData.ContentType,
                    Size = FileData.ContentLength,
                    Name = Path.GetFileName(FileData.FileName),
                    UserInfoUserID = userid
                };
                FileHelper.Add(file, gpmsDb);
                DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/upload"));
                if (!dir.Exists)
                {
                    dir.Create();
                }
                FileData.SaveAs(Path.Combine(Server.MapPath("~/upload"), file.FileID.ToString()));

                Response.Write("成功上传：" + file.Name);
            }
            catch (Exception ex)
            {
                Response.Write("上传失败！" + ex.Message);
            }
            
        }
        [HttpPost]
        public void UploadUserFile(HttpPostedFileBase FileData, string folder, string name)
        {
            try
            {
                Guid userid = Guid.Parse(FormsAuthentication.Decrypt(Request["token"]).UserData);
                GPMS.Model.File file = new Model.File()
                {
                    FileID = Guid.NewGuid(),
                    FileType = FileType.UserFile.ToString(),
                    MimeType = FileData.ContentType,
                    Size = FileData.ContentLength,
                    Name = Path.GetFileName(FileData.FileName),
                    UserInfoUserID = userid
                };
                FileHelper.Add(file, gpmsDb);
                DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/upload"));
                if (!dir.Exists)
                {
                    dir.Create();
                }
                FileData.SaveAs(Path.Combine(Server.MapPath("~/upload"), file.FileID.ToString()));

                Response.Write("成功上传："+file.Name);
            }
            catch (Exception ex)
            {
                Response.Write("上传失败！"+ ex.Message);
            }
            
        }

        public ActionResult Delete(Guid id)
        {
            return Confirm(string.Format("确定要删除此文件： {0} 吗？", gpmsDb.Files.FirstOrDefault(f => f.FileID == id).Name));
        }

        [HttpPost]
        public ActionResult Delete(Guid id,FormCollection collection)
        {
            try
            {
                GPMS.Model.File file = gpmsDb.Files.FirstOrDefault(f => f.FileID == id);
                FileInfo trueFile = new FileInfo(Path.Combine(Server.MapPath("~/upload"), id.ToString()));
                trueFile.Delete();
                gpmsDb.Files.DeleteObject(file);
                gpmsDb.SaveChanges();
                return Success("删除成功！！");
            }
            catch (Exception ex)
            {
                return JsonError("删除失败：" + ex.Message);
            }
        }

        public FileResult Download(Guid id)
        {
            GPMS.Model.File file = FileHelper.Get(id, gpmsDb);
            DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/upload"));
            if (!dir.Exists)
            {
                dir.Create();
            }
            return File(Path.Combine(Server.MapPath("~/upload"), file.FileID.ToString()),
                file.MimeType, file.Name);

        }

        public ActionResult List()
        {
            string type=FileType.UserFile.ToString();
            return View(gpmsDb.Files.Where(f => f.FileType != type).ToList());
        }

        public ActionResult UserFile(int? id)
        {
            //禁止页面被缓存
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Today.AddYears(-2));
            PagedList<File> list = FileHelper.GetUserFileList(AccountHelper.GetLoginUserID(Request), id ?? 1, gpmsDb);
            if (Request.IsAjaxRequest())
            {
                return PartialView("UserFileList", list);
            }
            return View(list);
        }

    }
}
